import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author DASK
 * @date 2020/3/17 23:02
 * @description //TODO 登录路径拦截器
 */
public class LoginServlet extends HttpServlet {
    private static final int ONE_DAY = 60 * 60 * 24;
    private String username;
    private String password;

    @Override
    public void init() throws ServletException {
        super.init();
        username = getInitParameter("username");
        password = getInitParameter("passwd");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=UTF-8");
        //判断是否已经登录，已经登录则则直接跳转到登陆成功界面，
        // 同时刷新cookie记录
        for (Cookie cookie : req.getCookies()) {
            if ("isLogin".equals(cookie.getName())) {
                if ("1".equals(cookie.getValue())) {
                    cookie.setMaxAge(ONE_DAY);//刷新cookie
                    resp.addCookie(cookie);
                    resp.sendRedirect("/suc.jsp");
                    return;
                }
            }
        }
        //没有登录则默认跳转到登录界面
        resp.sendRedirect("/login.jsp");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //判断密码是否正确
        resp.setContentType("application/json; charset=utf-8");// 指定返回的格式为JSON格式
        resp.setCharacterEncoding("UTF-8");
        PrintWriter writer = resp.getWriter();
        if (username.equals(req.getParameter("username"))
                && password.equals(req.getParameter("passwd"))
        ) {
            //密码正确则跳转到登录成功界面，同时配置cookie
            Cookie cookie = new Cookie("isLogin", "1");
            cookie.setMaxAge(60 * 60 * 24);
            resp.addCookie(cookie);
            writer.write("{\"OK\":\"true\"}");
        } else {
            //密码错误，则返回json给js用于弹出错误提示对话框
            writer.write("{\"OK\":\"false\"}");
        }
        writer.flush();
        writer.close();
    }


}
